﻿#region License

// Another free, open solution by someone who gets it.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace Patterns.Xml
{
	/// <summary>
	/// 	Defines a dictionary-based implementation of <see cref = "IXmlNamespaceResolver" />.
	/// </summary>
	public class NamespaceResolver : Dictionary<string, string>, IXmlNamespaceResolver
	{
		#region IXmlNamespaceResolver Members

		/// <summary>
		/// 	Gets a collection of defined prefix-namespace mappings that are currently in scope.
		/// </summary>
		/// <param name = "scope">An <see cref = "T:System.Xml.XmlNamespaceScope" /> value that specifies the type of namespace nodes to return.</param>
		/// <returns>
		/// 	An <see cref = "T:System.Collections.IDictionary" /> that contains the current in-scope namespaces.
		/// </returns>
		public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
		{
			return this;
		}

		/// <summary>
		/// 	Gets the namespace URI mapped to the specified prefix.
		/// </summary>
		/// <param name = "prefix">The prefix whose namespace URI you wish to find.</param>
		/// <returns>
		/// 	The namespace URI that is mapped to the prefix; null if the prefix is not mapped to a namespace URI.
		/// </returns>
		public string LookupNamespace(string prefix)
		{
			return this[prefix];
		}

		/// <summary>
		/// 	Gets the prefix that is mapped to the specified namespace URI.
		/// </summary>
		/// <param name = "namespaceName">The namespace URI whose prefix you wish to find.</param>
		/// <returns>
		/// 	The prefix that is mapped to the namespace URI; null if the namespace URI is not mapped to a prefix.
		/// </returns>
		public string LookupPrefix(string namespaceName)
		{
			return this.Where(entry => entry.Value == namespaceName).Select(entry => entry.Key).FirstOrDefault();
		}

		#endregion
	}
}